import router from './router'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useCache } from '@/hooks/web/useCache'
import type { RouteRecordRaw } from 'vue-router'
import { useTitle } from '@/hooks/web/useTitle'
import { useNProgress } from '@/hooks/web/useNProgress'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { useBasicStoreWithOut } from '@/store/modules/basic'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { setupUI } from '@/utils/initUI'
import { getWithoutRoute } from '@/utils/routerHelper'

const permissionStore = usePermissionStoreWithOut()

const basicStore = useBasicStoreWithOut()

const appStore = useAppStoreWithOut()

const { wsCache } = useCache()

const { start, done } = useNProgress()

const { loadStart, loadDone } = usePageLoading()

const whiteList = ['/login'] // 不重定向白名单

// 只执行一次，是否缓存了FirstQuery
let isCachedFirstQuery = false

router.beforeEach(async (to, from, next) => {
  start()
  loadStart()
  // 如果传了token，使用无ui路由渲染组件，组件使用 ../views/ + to.path的后2位/取组件
  const withoutLogin = to.query?.token
  if (withoutLogin) {
    const allRoutes = router.getRoutes()
    if (allRoutes.find((x) => x.path == to.path)) {
      next()
    } else {
      router.addRoute(getWithoutRoute(to)) // 动态添加可访问路由表
      next({ ...to, replace: true })
    }
    return
  }
  if (!basicStore.getIsLoadedConfig) {
    // 加载项目配置
    await basicStore.fetchConfigs()
    // 根据配置设置UI
    setupUI(basicStore.getUI)
  }
  // 是否需要校验license
  const isActivationLicense = basicStore.getIsActivationLicense
  if (isActivationLicense) {
    await basicStore.checkLicense()
  }
  // 保存首次参数
  const isUseFirstQuery = basicStore.getUseFirstQuery
  if (isUseFirstQuery) {
    if (!isCachedFirstQuery) {
      isCachedFirstQuery = true
      basicStore.cacheFirstQuery()
    }
    const firstQuery = basicStore.getFirstQuery
    const mergedQuery = { ...firstQuery, ...to.query }
    // 路由跳转时，当带上FirstQuery后不相同，重定向路由带上参数
    if (JSON.stringify(to.query) !== JSON.stringify(mergedQuery)) {
      return next({
        ...to,
        query: mergedQuery,
        replace: true
      })
    }
  }
  // 是否需要登录
  const isLoginVerify = basicStore.getIsLoginVerify
  if (wsCache.get(appStore.getToken) || !isLoginVerify) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      // if (!dictStore.getIsSetDict) {
      //   // 获取所有字典
      //   const res = await getDictApi()
      //   if (res) {
      //     dictStore.setDictObj(res.data)
      //     dictStore.setIsSetDict(true)
      //   }
      // }
      if (permissionStore.getIsAddRouters) {
        next()
        return
      }
      // 加载路由配置
      if (!permissionStore.getIsLoadedConfig) {
        await permissionStore.fetchConfigs()
        // 不需要登录模拟写入token
        if (!isLoginVerify) {
          await permissionStore.setDefaultLogin()
        } else {
          await permissionStore.fetchUserInfo()
        }
        // 开发者可根据实际情况进行修改
        // const userInfo = wsCache.get(appStore.getUserInfo)
        // const token = wsCache.get(appStore.getToken)
        // console.log(token, userInfo)

        // 是否使用动态路由
        permissionStore.getAddRouters.forEach((route) => {
          router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
        })
      }
      const redirectPath = from.query.redirect || to.path
      const redirect = decodeURIComponent(redirectPath as string)
      const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
      permissionStore.setIsAddRouters(true)
      next(nextData)
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
    }
  }
})

router.afterEach((to) => {
  useTitle(to?.meta?.title as string)
  done() // 结束Progress
  loadDone()
})
